import axios from 'axios'
import {Loading, Message} from 'element-ui'

let timeOut = null
let options = {}
let loading = null

axios.interceptors.request.use(function (config) {
  return config
}, function (error) {
  if (timeOut != null) {
    window.clearTimeout(timeOut)
    timeOut = null
  }
  if (loading != null) {
    loading.close()
    loading = null
  }
  return Promise.reject(error)
})

axios.interceptors.response.use(function (response) {
  return response
}, function (error) {
  if (timeOut != null) {
    window.clearTimeout(timeOut)
    timeOut = null
  }
  if (loading != null) {
    loading.close()
    loading = null
  }
  return Promise.reject(error)
})

export const http = axios

export const common = {
  vue: null,
  loadingMessage: function (message) {
    options.text = message
    if (timeOut == null) {
      timeOut = window.setTimeout(function () {
        loading = Loading.service(options)
      }, 300)
    }
  },
  errorMessage: function (message) {
    if (this.vue != null) {
      this.vue.$store.commit("errorMessage", message);
    }
  },
  clearErrorMessage: function () {
    if (this.vue != null) {
      this.vue.$store.commit("errorMessage", null)
    }
  },
  closeMessage: function () {
    if (timeOut != null) {
      window.clearTimeout(timeOut)
      timeOut = null
    }
    if (loading != null) {
      loading.close()
      loading = null
    }
  },
  datas: function (respon) {
    if (respon.status == 200) {
      const data = respon.data
      if (data.code == 0 && data.datas != null) {
        return data
      } else {
        if (data.code == 12) { //用户未登录错误
          if (data.datas != null && data.datas.length > 0) {
            this.errorMessage("亲!里面有些小秘密，需要认证才能查看哦。");
            this.vue.$router.push(data.datas[0])
          }
        } else if (data.code == 20) { //用户未绑定错误
          this.errorMessage("用户尚未绑定，请先完成绑定操作。")
          this.vue.$router.push('/shop/bind.html')
        } else {
          if (this.vue.$store.state.errorMessage == null) {
            let msg = data.message
            if (msg == null) {
              msg = '未知的错误,请联系系统管理员!'
            }
            Message({
              message: msg,
              type: 'error'
            });
          }
        }
      }
    }
    return null
  },
  scrf: async () => {
    let response = await http.get('/api/public/csrf')
    const tokenData = response.data.datas
    http.defaults.headers = {'X-CSRF-TOKEN': tokenData[0]}
    return tokenData[0]

  },
  getStore: function (name) {
    if (!name) return null
    return window.localStorage.getItem(name)
  },

  removeStore: function (name) {
    if (!name) return null
    window.localStorage.removeItem(name)
  },

  setStore: function (name, content) {
    if (!name) return null
    if (typeof content !== 'string') {
      content = JSON.stringify(content)
    }
    window.localStorage.setItem(name, content)
  },
  toJson: function (object) {
    if (object == null || object == undefined) {
      return null
    }
    this.emptyProperty(object)
    const result = JSON.stringify(object)
    return result
  },
  isEmpty: function (object) {
    for (var name in object) {
      return false
    }
    return true
  },
  emptyProperty: function (object) {
    for (var i in object) {
      var value = object[i]
      if (typeof value === 'object') {
        if (Array.isArray(value)) {
          if (value.length == 0) {
            delete object[i]
            continue
          }
        }
        this.emptyProperty(value)
        if (this.isEmpty(value)) {
          delete object[i]
        }
      } else {
        if (value === null || value === undefined) {
          delete object[i]
        }
      }
    }
  },
  app: async function (init) {
    const token = await this.scrf()
    return init()
  },
  remoteLoad: function (url, hasCallback) {
    return createScript(url);

    /**
     * 创建script
     * @param url
     * @returns {Promise}
     */
    function createScript(url) {
      const scriptElement = document.createElement('script');
      document.body.appendChild(scriptElement);

      const promise = new Promise((resolve, reject) => {
        scriptElement.addEventListener('load', e => {
          removeScript(scriptElement);
          if (!hasCallback) {
            resolve(e);
          }
        }, false);

        scriptElement.addEventListener('error', e => {
          removeScript(scriptElement);
          reject(e);
        }, false);

        if (hasCallback) {
          window.____callback____ = function () {
            resolve();
            window.____callback____ = null;
          }
        }

      });

      if (hasCallback) {
        url += '&callback=____callback____'
      }

      scriptElement.src = url;

      return promise;
    }

    function removeScript(scriptElement) {
      document.body.removeChild(scriptElement);
    }
  }
}
